<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>PulsarCommander SSE Client</title>
    <style>
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: #f7f9fa;
            color: #222;
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 820px;
            margin: 40px auto;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
            padding: 32px 28px 24px 28px;
        }

        h2 {
            margin-top: 0;
            color: #2a5d9f;
            letter-spacing: 1px;
        }

        #commandInput {
            width: 100%;
            font-size: 0.95em;
            border-radius: 8px;
            border: 1px solid #bfc9d1;
            padding: 10px;
            margin-bottom: 12px;
            box-sizing: border-box;
            background: #f4f7fa;
            transition: border 0.2s;
        }

        #commandInput:focus {
            border: 1.5px solid #2a5d9f;
            outline: none;
            background: #fff;
        }

        button {
            background: linear-gradient(90deg, #2a5d9f 60%, #4e8ad1 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 28px;
            font-size: 1.1em;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(42, 93, 159, 0.08);
            margin-bottom: 18px;
            transition: background 0.2s, box-shadow 0.2s;
        }

        button:hover {
            background: linear-gradient(90deg, #1d3e6b 60%, #2a5d9f 100%);
            box-shadow: 0 4px 16px rgba(42, 93, 159, 0.13);
        }

        #status {
            margin: 10px 0 8px 0;
            font-weight: bold;
            color: #2a5d9f;
            min-height: 24px;
        }

        #events {
            background: #f4f7fa;
            color: #2f2f33;
            border: 1px solid #e0e6ed;
            border-radius: 8px;
            padding: 14px;
            min-height: 120px;
            white-space: pre;
            margin-top: 0;
            box-sizing: border-box;
            max-height: 320px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>🚀 PulsarRPA Commander</h2>
    <label for="commandInput">🤖 What do you want me to do?</label>
    <textarea id="commandInput" rows="6" cols="60">
        Go to https://www.amazon.com/dp/B0C1H26C46

        After browser launch: clear browser cookies.
        After page load: scroll to the middle.

        Summarize the product.
        Extract: product name, price, ratings.
        Find all links containing /dp/.
    </textarea><br>
    <button id="reviseButton" onclick="reviseCommand()">✨ Refine</button>
    <button id="submitButton" onclick="submitCommand()" style="float: right;">🚀 Submit</button>
    <div id="status"></div>
    <div id="events">

    </div>
    <div id="finalResultContainer" style="display:none;margin-top:18px;">
        <h3 style="color:#2a5d9f;">🎯 Final Result</h3>
        <pre id="finalResult"
             style="background:#f4f7fa;border:1px solid #e0e6ed;border-radius:8px;padding:14px;font-size:1em;color:#222;white-space:pre;overflow-x:auto;"></pre>
    </div>
</div>
<script>
    let baseUrl = "http://localhost:8182/api"
    let commandUrl = baseUrl + "/commands/plain?mode=async"
    let streamBaseUrl = baseUrl + "/commands/{id}/stream"
    let revisionUrl = baseUrl + "/command-revisions"

    function reviseCommand() {
        const reviseButton = document.getElementById('reviseButton');
        const commandInput = document.getElementById('commandInput');
        const command = document.getElementById('commandInput').value.trim();
        const status = document.getElementById('status');
        const events = document.getElementById('events');
        status.textContent = '⏳ Refining...';
        events.textContent = '';

        reviseButton.disabled = true;

        fetch(revisionUrl, {
            method: 'POST',
            headers: {'Content-Type': 'text/plain'},
            body: command
        }).then(res => res.text()).then(text => {
            commandInput.value = text
            status.textContent = "✅ Refined.";
            reviseButton.disabled = false;
        }).catch(err => {
            status.textContent = '❌ Error: ' + err.message;
            reviseButton.disabled = false;
        });
    }

    function submitCommand() {
        const command = document.getElementById('commandInput').value.trim();
        const status = document.getElementById('status');
        const events = document.getElementById('events');
        status.textContent = '⏳ Submitting...';
        events.textContent = '';
        fetch(commandUrl, {
            method: 'POST',
            headers: {'Content-Type': 'text/plain'},
            body: command
        }).then(response => {
            if (!response.ok) throw new Error('❌ Failed to submit command');
            return response.text();
        }).then(id => {
            status.textContent = '✅ Submitted. id: ' + id;
            listenSSE(id);
        }).catch(err => {
            status.textContent = '❌ Error: ' + err.message;
        });
    }

    function listenSSE(id) {
        try {
            listenSSE0(id)
        } catch (e) {
            console.error("Error in SSE listener: ", e);
            const status = document.getElementById('status');
            status.textContent = '❌ Error in SSE listener: ' + e.message;
        }
    }
    function listenSSE0(id) {
        const status = document.getElementById('status');
        const events = document.getElementById('events');

        // Clear previous events
        events.innerHTML = '';

        // Close any existing connection
        if (window.activeEventSource) {
            console.log("Closing previous connection");
            window.activeEventSource.close();
        }

        const url = streamBaseUrl.replace("{id}", id);
        console.log("Connecting to SSE endpoint:", url);

        // Add connection info to events display
        events.innerHTML += `<pre style="color:#2a5d9f">Connecting to: ${url}</pre>`;

        const es = new EventSource(url);
        window.activeEventSource = es;

        // Add raw data display function
        function displayRawData(data, type) {
            console.log(`Raw ${type} data:`, data);
            const rawElement = document.createElement('pre');
            rawElement.textContent = `[${type}] ${data}`;
            rawElement.style.marginBottom = "8px";
            rawElement.style.color = "#666";
            rawElement.style.fontSize = "0.8em";
            events.appendChild(rawElement);
            events.scrollTop = events.scrollHeight;
        }

        es.addEventListener('open', function(e) {
            console.log("SSE connection opened", e);
            status.textContent = "Connected to stream.";
            displayRawData("Connection opened", "open");
        });

        es.addEventListener('message', function(e) {
            displayRawData(e.data, "message");
            // Try to process if possible, but display raw data regardless
            try {
                if (e.data && e.data.trim()) {
                    if (e.data.trim().startsWith('{')) {
                        const data = JSON.parse(e.data);
                        updateStatus(data);
                    }
                }
            } catch (err) {
                console.error("Error processing event:", err);
            }
        });

        // Listen for custom event types
        ["command", "update", "status"].forEach(eventType => {
            es.addEventListener(eventType, function(e) {
                displayRawData(e.data, eventType);
                try {
                    if (e.data && e.data.trim().startsWith('{')) {
                        const data = JSON.parse(e.data);
                        updateStatus(data);
                    }
                } catch (err) {
                    console.error(`Error processing ${eventType} event:`, err);
                }
            });
        });

        es.addEventListener('error', function(e) {
            console.error("SSE error:", e);
            displayRawData("Connection error", "error");
            es.close()

            if (es.readyState === EventSource.CLOSED) {
                status.textContent = "SSE connection closed";
            } else if (es.readyState === EventSource.CONNECTING) {
                status.textContent = "Connection lost - reconnecting...";
            }
        });

        function updateStatus(data) {
            const finalResultContainer = document.getElementById('finalResultContainer');
            const finalResult = document.getElementById('finalResult');

            if (data.statusCode === 404) {
                status.textContent = 'Not Found';
            } else if (data.statusCode === 500) {
                status.textContent = 'Finished: ERROR';
            } else if (data.isDone) {
                status.textContent = 'Finished ' + data.status;
            } else {
                status.textContent = 'Processing: ' + (data.status || '');
                return;
            }

            finalResultContainer.style.display = '';
            finalResult.textContent = JSON.stringify(data, null, 2);
        }
    }
</script>
</body>
</html>
